package io.github.cubelitblade.librarymanagementbackend.controller;

import io.github.cubelitblade.librarymanagementbackend.dto.UserBookRequestDTO;
import io.github.cubelitblade.librarymanagementbackend.service.UserFavoriteFacade;
import io.github.cubelitblade.librarymanagementbackend.utils.BusinessStatus;
import io.github.cubelitblade.librarymanagementbackend.utils.ResultContext;
import io.github.cubelitblade.librarymanagementbackend.vo.FavoriteResponseVO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {
    private final UserFavoriteFacade userFavoriteFacade;
    FavoriteController(UserFavoriteFacade userFavoriteFacade) {
        this.userFavoriteFacade = userFavoriteFacade;
    }

    @PostMapping
    public ResponseEntity<ResultContext<FavoriteResponseVO>> addToFavorites(@RequestBody UserBookRequestDTO userBookRequestDTO) {
        return ResponseEntity.ok(ResultContext.succeed(userFavoriteFacade.addToFavorites(userBookRequestDTO)));
    }

    @DeleteMapping("/{favoriteId}")
    public ResponseEntity<Void> removeFromFavorites(@PathVariable Integer favoriteId) {
        userFavoriteFacade.removeFromFavorites(favoriteId);
        return ResponseEntity.noContent().build();
    }

    @PatchMapping("/{favoriteId}")
    public ResponseEntity<ResultContext<Boolean>> toggleFavoriteActive(@PathVariable Integer favoriteId) {
        return ResponseEntity.ok(ResultContext.succeed(userFavoriteFacade.toggleFavoriteActive(favoriteId)));
    }

    @GetMapping
    public ResponseEntity<ResultContext<FavoriteResponseVO>> getFavorite(@RequestParam Integer userId, @RequestParam Integer bookId) {
        FavoriteResponseVO favoriteResponseVO = userFavoriteFacade.getFavorite(userId, bookId);

        if (favoriteResponseVO == null) {
            return ResponseEntity.ok(
                    new ResultContext<>(
                            BusinessStatus.FAVORITE_RECORD_NOT_FOUND.getBusinessStatusCode(),
                            "Favorite record not found",
                            null
                    )
            );
        }

        return ResponseEntity.ok(ResultContext.succeed(favoriteResponseVO));
    }
}
